package com.timguan.render.web.common;

import com.timguan.render.api.api.B2CMallServiceReturnCode;
import com.timguan.render.service.common.B2CMallServiceConfig;
import net.pocrd.entity.ServiceException;
import net.pocrd.entity.ServiceRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理topic异常的Listener，可以自定义试图渲染或者重定向
 * Created by guankaiqiang on 2014/12/3.
 */
public class TopicNotFoundListener extends ServiceExceptionListener {
    private static final Logger logger = LoggerFactory.getLogger(TopicNotFoundListener.class);

    public TopicNotFoundListener() {
        super();
    }

    @Override
    public void initAcceptCodes() {
        setCode(B2CMallServiceReturnCode._C_TOPIC_NOT_FOUND);
    }

    /**
     * topic找不到直接指向404
     *
     * @param event
     * @param request
     * @param response
     * @return
     */
    @Override
    public ModelAndView serviceExceptionEventHandle(int event, ServiceException se, ServiceRuntimeException sre, HttpServletRequest request, HttpServletResponse response) {
        if (B2CMallServiceReturnCode._C_TOPIC_NOT_FOUND == event) {
            try {
                if (!response.isCommitted()) {
                    response.sendRedirect(B2CMallServiceConfig.getInstance().getPageNotFoundSite());
                } else {
                    logger.warn("response has been commited!");
                }
            } catch (IOException e) {
                logger.error("redirect failed!", e);
            }
        }
        return null;
    }
}
